#!/bin/sh
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Ian Moore <imooreyahoo@gmail.com>
# @copyright Copyright (c) 2011 Ian Moore
#
# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions


MYSQL_CONFIG="/etc/mysql/conf.d/openmediavault-mysql.cnf";
MYSQL_INIT="isc-mysql-server"

# Enable/disable service
if [ "$(omv_config_get "//services/mysql/enable")" != "1" ]; then
	if [ -e /etc/apache2/sites-enabled/phpmyadmin ]; then
		a2dissite phpmyadmin
	fi
	update-rc.d mysql disable
	exit 0
fi

# Create mysql config file
cat <<EOF > ${MYSQL_CONFIG}
# config for openmediavault-mysql

[mysqld]
EOF

xmlstarlet sel -t -m "//services/mysql" \
 -i "enable-networking != 1" -o "skip-networking" -n -b \
 -i "port != ''" -v "concat('port = ', port)" -n -b \
 -i "bindaddress != ''" -v "concat('bind-address = ', bindaddress)" -n -b \
 -i "data-root != ''" -v "concat('datadir = ', data-root)" -n -b \
 -i "string-length(extraoptions) > 0" -v "extraoptions" -n -b \
${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${MYSQL_CONFIG}

if [ "$(omv_config_get "//services/mysql/enable-phpmyadmin")" != "1" ]; then
    if [ -e /etc/apache2/sites-enabled/phpmyadmin ]; then
        a2dissite phpmyadmin
    fi
else
    if [ ! -e /etc/apache2/sites-enabled/phpmyadmin ]; then
        a2ensite phpmyadmin
    fi
fi

update-rc.d mysql enable
update-rc.d mysql defaults
